package com.venusj.redis02.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author venusj
 * @date 2021/3/21
 */
@RestController
@RequestMapping(value = "/good")
public class GoodController {

    private static final String GOOD_LOCK = "GOOD_LOCK";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private Redisson redisson;

    @GetMapping("/buy_Goods")
    public String buy_Goods() {
        String value = UUID.randomUUID().toString() + Thread.currentThread().getName();
        // 分布式锁
        RLock lock = redisson.getLock(GOOD_LOCK);
        lock.lock();
        try {
            // 1.查看库存数量
            String result = stringRedisTemplate.opsForValue().get("goods:001");
            int goodsNumber = result == null ? 0 : Integer.parseInt(result);

            // 2.卖商品
            if (goodsNumber > 0) {
                int realNumber = goodsNumber - 1;
                // 3.成功买入，库存减少一件
                stringRedisTemplate.opsForValue().set("goods:001", String.valueOf(realNumber));
                System.out.println("成功买入商品，库存还剩下：" + realNumber + "服务端口：" + serverPort);
                return "成功买入商品，库存还剩下：" + realNumber + "服务端口：" + serverPort;
            } else {
                System.out.println("商品卖完" + "服务端口：" + serverPort);
            }
            return "商品卖完！" + "服务端口：" + serverPort;
        } finally {
            // 防止超高并发 出现异常
            if(lock.isLocked())
            {
                if(lock.isHeldByCurrentThread())
                {
                    lock.unlock();
                }
            }
        }

    }
}
